package sd_services

import (
	"fmt"
	"log"
	"xiehui-service/app/models/sd_models"
	"xiehui-service/global"

	"go.uber.org/zap"
)

type pieceService struct {
}

var PieceService = new(pieceService)

// 查询盘信息
func (pieceService *pieceService) PieceList(stamp float64, num int64) (pieces []sd_models.Piece, err error) {
	err = global.App.MSACCESS.Ping()
	if err != nil {
		log.Println("PieceList ping==>>", err)
		global.App.Log.Error("查询盘数据失败：", zap.Any("数据库联接", "ping失败"))
		return nil, err
	}
	rows, err := global.App.MSACCESS.Query(fmt.Sprintf("select Top %d * from Piece where Stamp > %.10f order by Stamp asc", num, stamp))
	if err != nil {
		log.Println("PieceList query==>>", err)
		global.App.Log.Error("查询盘数据失败：", zap.Any("Query查询失败", err))
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var pieceItem sd_models.Piece

		if err := rows.Scan(&pieceItem.ID, &pieceItem.Produce, &pieceItem.RecID, &pieceItem.Recipe, &pieceItem.Serial, &pieceItem.Blender, &pieceItem.DatTim, &pieceItem.BldTim, &pieceItem.PieAmnt, &pieceItem.Lands, &pieceItem.Temper, &pieceItem.PieErr, &pieceItem.Data, &pieceItem.Flag, &pieceItem.Stamp, &pieceItem.BldDrOpenTim); err != nil {
			log.Println("PieceList scan==>>", err)
		}
		pieces = append(pieces, pieceItem)
	}

	if err := rows.Err(); err != nil {
		log.Println("PieceList rows.err==>>", err)
		global.App.Log.Error("查询盘数据失败：", zap.Any("查询失败", err))
		return nil, err
	}

	return pieces, nil
}

func (pieceService *pieceService) GetByProduce(produceId string) (pieces []sd_models.Piece, err error) {
	err = global.App.MSACCESS.Ping()
	if err != nil {
		log.Println("GetByProduce ping==>>", err)
		global.App.Log.Error("查询盘数据失败：", zap.Any("数据库联接", "ping失败"))
		return nil, err
	}
	rows, err := global.App.MSACCESS.Query(fmt.Sprintf("select * from Piece where Produce = '%s' order by Stamp asc", produceId))
	if err != nil {
		log.Println("GetByProduce query==>>", err)
		global.App.Log.Error("查询盘数据失败：", zap.Any("Query查询失败", err))
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var pieceItem sd_models.Piece

		if err := rows.Scan(&pieceItem.ID, &pieceItem.Produce, &pieceItem.RecID, &pieceItem.Recipe, &pieceItem.Serial, &pieceItem.Blender, &pieceItem.DatTim, &pieceItem.BldTim, &pieceItem.PieAmnt, &pieceItem.Lands, &pieceItem.Temper, &pieceItem.PieErr, &pieceItem.Data, &pieceItem.Flag, &pieceItem.Stamp, &pieceItem.BldDrOpenTim); err != nil {
			log.Println("GetByProduce scan==>>", err)
		}
		pieces = append(pieces, pieceItem)
	}

	if err := rows.Err(); err != nil {
		log.Println("GetByProduce rows.err==>>", err)
		global.App.Log.Error("查询盘数据失败：", zap.Any("查询失败", err))
		return nil, err
	}

	return pieces, nil
}
